import router from '@/router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
console.log(import.meta.env.VITE_APP_API_PATH)
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_API_PATH, //api_test
  timeout: 5000
})
service.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `${token}`
  }
  return config
})
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data.code === 0) {
        ElMessage.error(response.data.message)
        return Promise.reject(new Error(response.statusText))
      }
      return response.data
    } else {
      ElMessage.error('请求超时，请刷新重试')
      return Promise.reject(new Error(response.statusText))
    }
  },
  (err) => {
    console.log(err.response)
    if (err.response.status === 401) {
      localStorage.removeItem('token')
      router.push('/login')
    } else {
      ElMessage.error(err.response.data.message)
    }
  }
)
export default service
